package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import object.wxtemplate.GetP2UMsg;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import service.DeviceService;
import service.UserService;
import utils.JsonUtil;
import utils.MD5Helper;
import config.SysConfig;

/**
 * 调用邮宝API
 * @author hdq
 *
 */
@Controller
@RequestMapping("useYBApi")
public class UseYBApiController {
	
	private static Logger logger = Logger.getLogger(UseYBApiController.class);
	
	@Autowired
	private UserService userService;
	@Autowired
	private DeviceService deviceService;
	
	/**
	 * 远程开锁操作界面
	 * 
	 */
	@RequestMapping("openLockUI")
	public String openLockUI(
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "jsonData") String jsonData,
			HttpServletRequest httpRequest) {
		try {
			String sign=MD5Helper.getMD5Str("openId="+openId+"&key="+SysConfig.agent_key);
			httpRequest.setAttribute("resultCode","0");
			httpRequest.setAttribute("openId",openId);
			httpRequest.setAttribute("jsonData",jsonData);
			httpRequest.setAttribute("sign",sign);
			httpRequest.setAttribute("href",SysConfig.openLock_url);
		} catch (Exception e) {
			logger.error(e.getMessage());
			httpRequest.setAttribute("resultCode","-1");
			httpRequest.setAttribute("resultMsg", "request failed");
		}
		return "forward:/web/openLockUI.jsp";
	}
	
	/**
	 * 远程开锁
	 */
	@RequestMapping("openLock")
	public String openLock(
			@RequestParam(value = "openId") String openId,
			@RequestParam(value = "sign") String sign,
			@RequestParam(value = "jsonData") String jsonData,
			HttpServletRequest httpRequest) {
		InputStream msgStream = null;
		BufferedReader rd = null;
		String returnlMsg = "";
		try {
			if(checkSign(openId,SysConfig.agent_key,sign)){
				GetP2UMsg getP2UMsg=JsonUtil.jsonToBean(jsonData, GetP2UMsg.class);
				Integer userId=getUserIdByOpenId(getP2UMsg.getUserMobileNum());
				int deviceId=deviceService.getDeviceId(getP2UMsg.getDeviceSeq());
				String newOpenLockUrl = SysConfig.api_openLock_url
						+ String.format("?operaterID=%s&serTime=%s&parcelNum=%s&mobileNum=%s&boxNum=%s&opType=%s&terminalID=%s",
								userId+"", new Date().getTime()+"", getP2UMsg.getParcelNum(), getP2UMsg.getUserMobileNum(), getP2UMsg.getBoxNum()+"", "1", deviceId+"");
				logger.info("newOpenLockUrl: " + newOpenLockUrl);
				URL url = new URL(newOpenLockUrl);
				URLConnection con = url.openConnection();
				con.setAllowUserInteraction(false);
				msgStream = con.getInputStream();
				rd = new BufferedReader(new InputStreamReader(msgStream, "UTF-8"));
				StringBuilder tempStr = new StringBuilder();
				while (rd.read() != -1) {
					tempStr.append(rd.readLine());
				}
				if (new String(tempStr).contains("\"responseCode\":\"00000\"")) {
		        	returnlMsg += "打开："+ getP2UMsg.getDevBranchAddr()+"--><br>" + getP2UMsg.getDeviceName()+"-"+getP2UMsg.getBoxNum() + "号柜门<br>指令下发成功。<br><br>";
		        	returnlMsg += "<p>1分钟后如若柜门没打开，请联系"+getP2UMsg.getDevBranchHotLine()+"</p>";
		        	httpRequest.setAttribute("resultCode", 1);
					//httpRequest.setAttribute("returnlMsg", returnlMsg);
		        } else if (new String(tempStr).contains("\"responseCode\":\"00002\"")) {
		        	
		        	returnlMsg= "您的包裹已取，如果错误请联系客服";
					httpRequest.setAttribute("resultCode", -1);
		        }else {
		        	returnlMsg += "打开：" + getP2UMsg.getDevBranchAddr() + "<br>"+getP2UMsg.getBoxNum() + "号柜门指令下发失败.<br><br>";
		        	returnlMsg += "<p>请联系"+getP2UMsg.getDevBranchHotLine()+"</p>";
		        	httpRequest.setAttribute("resultCode", -1);
		        	//httpRequest.setAttribute("returnlMsg", returnlMsg);
					//httpRequest.setAttribute("returnlMsg", returnlMsg);
				}
			}else{
				returnlMsg= "签名验证失败";
				httpRequest.setAttribute("resultCode", "40001");
			}
			
	} catch (Exception e) {
		returnlMsg = "服务器繁忙,请稍后再试";
		httpRequest.setAttribute("code", -1);
		//httpRequest.setAttribute("returnlMsg", returnlMsg);
	} finally {
		try {
			if (rd != null) {
				rd.close();
			}
		} catch (IOException e) {
			returnlMsg= "服务器繁忙,请稍后再试";
			httpRequest.setAttribute("code", -1);
			//httpRequest.setAttribute("returnlMsg", returnlMsg);
		} finally {
			if (msgStream != null) {
				try {
					msgStream.close();
				} catch (IOException e) {
					returnlMsg= "服务器繁忙,请稍后再试";
					httpRequest.setAttribute("code", -1);
					//httpRequest.setAttribute("returnlMsg", returnlMsg);
				}
			}
		}
	}
	httpRequest.setAttribute("returnlMsg", returnlMsg);
	return "forward:/web/returnMsg.jsp";
	}
	
	private Integer getUserIdByOpenId(String openId){
		return userService.getUserIdByOpenID(openId);
	};
	
	private boolean checkSign(String openId,String key,String sign){
		String checkParamStr="openId="+openId+"&key="+key;
		String iSign=MD5Helper.getMD5Str(checkParamStr);
		sign.equals(iSign);
		return sign.equals(iSign);
	};

}